package com.cloudcc.mobile.receiver;

import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Vibrator;
import android.support.v4.app.NotificationCompat;

import com.baidu.android.pushservice.PushManager;
import com.baidu.android.pushservice.PushMessageReceiver;
import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.bus.EventList.PushBindEvent;
import com.cloudcc.cloudframe.model.push.PushBindModel;
import com.cloudcc.cloudframe.util.LogUtils;
import com.cloudcc.cloudframe.util.SharePreferece;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.db.ApprovalDB;
import com.cloudcc.mobile.db.ChatMessageDB;
import com.cloudcc.mobile.db.EventDB;
import com.cloudcc.mobile.db.IMMessageDB;
import com.cloudcc.mobile.db.MessageDB;
import com.cloudcc.mobile.db.RecentDB;
import com.cloudcc.mobile.db.TaskDB;
import com.cloudcc.mobile.entity.IMMessage;
import com.cloudcc.mobile.entity.Message;
import com.cloudcc.mobile.entity.RecentItem;
import com.cloudcc.mobile.entity.chat.Approval;
import com.cloudcc.mobile.entity.chat.ChatMessage;
import com.cloudcc.mobile.entity.chat.Event;
import com.cloudcc.mobile.entity.chat.Task;
import com.cloudcc.mobile.manager.ConfigManager;
import com.cloudcc.mobile.manager.CloudCCPushManager;
import com.cloudcc.mobile.manager.UserManager;
import com.cloudcc.mobile.util.Json;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.view.activity.AboutMeActivty;
import com.cloudcc.mobile.view.activity.MessageActivity;
import com.cloudcc.mobile.view.activity.TaskManagementActivty;
import com.cloudcc.mobile.view.activity.WebViewActivity;
import com.cloudcc.mobile.view.wel.WelcomeActivity;
import com.lidroid.xutils.exception.DbException;

/**
 * 消息推送广播接收类 2000-系统消息 2001-待审批 2002-任务 2003-事件
 * 
 * @author Administrator
 * 
 */
public class MyPushMessageReceiver extends PushMessageReceiver {

	/*
	 * Push消息处理receiver。请编写您需要的回调函数， 一般来说： onBind是必须的，用来处理startWork返回值；
	 *onMessage用来接收透传消息； onSetTags、onDelTags、onListTags是tag相关操作的回调；
	 *onNotificationClicked在通知被点击时回调； onUnbind是stopWork接口的返回值回调

	 * 返回值中的errorCode，解释如下：
	 *0 - Success
	 *10001 - Network Problem
	 *10101  Integrate Check Error
	 *30600 - Internal Server Error
	 *30601 - Method Not Allowed
	 *30602 - Request Params Not Valid
	 *30603 - Authentication Failed
	 *30604 - Quota Use Up Payment Required
	 *30605 -Data Required Not Found
	 *30606 - Request Time Expires Timeout
	 *30607 - Channel Token Timeout
	 *30608 - Bind Relation Not Found
	 *30609 - Bind Number Too Many

	 * 当您遇到以上返回错误时，如果解释不了您的问题，请用同一请求的返回值requestId和errorCode联系我们追查问题。
	 *
	 */
	private static final String TAG = "push";

	private String neirong;
	private String name;

	@Override
	public void onBind(Context context, int errorCode, String appid,
			String userId, String channelId, String requestId) {
		String responseString = "onBind errorCode=" + errorCode + " appid="
				+ appid + " userId=" + userId + " channelId=" + channelId
				+ " requestId=" + requestId;
		LogUtils.d(TAG, "绑定回调：" + responseString);
		if (errorCode != 0) {
			return;
		}
		PushBindModel bind = new PushBindModel();
		bind.userId = userId;
		bind.channelId = channelId;
		bind.requestId = requestId;
		bind.appid = appid;
		CloudCCPushManager.getInstance().setPushBind(bind);
		//注册设备
		EventEngine.post(new PushBindEvent());
		if (!ConfigManager.getInstance().isAllowPush()) {
			PushManager.stopWork(context);
		}
	}

	/**
	 * 接收透传消息的函数。
	 * 
	 */
	@Override
	public void onMessage(Context context, String message,
			String customContentString) {
		LogUtils.d(TAG, "onMessage:" + message);
		NotificationManager manager = (NotificationManager) context
				.getSystemService(context.NOTIFICATION_SERVICE);
		PendingIntent contentIntent = null;
		// 震动提醒
		SharePreferece share = new SharePreferece(context);
		boolean isMusic = ConfigManager.getInstance().isAllowPushSound();//音乐
		boolean isVibrate = ConfigManager.getInstance().isAllowPushVibrate();//震动
		String showmsg = "";
		try {
			JSONObject json = new JSONObject(message);
			String messageType = json.getString("messageType");
			if (messageType.equals("message")) {// 通知消息
				String function = json.getString("function");
				if (function.equals("showmsg")) {
					boolean isChat = json.has("chatterType");
					if (!isChat) {// 是系统消息不是chat消息
						tiXing(context, isVibrate, isMusic);// 系统消息提醒（声音，震动）
						showmsg = json.getString("content");
						Message mes = new Message();
						int a = showmsg.lastIndexOf("[");
						if (a != -1) {
							neirong = showmsg.substring(0, a);
							name = showmsg.substring(a + 1,
									showmsg.length() - 1);
							mes.setContext(neirong);
							mes.setTime(Tools.getTime(System
									.currentTimeMillis()));
							mes.setName(name);
							mes.setIsNew("1");
						} else {
							mes.setContext(showmsg);
							mes.setTime(Tools.getTime(System
									.currentTimeMillis()));
							mes.setIsNew("1");
							// 核对死

						}
						MessageDB db = new MessageDB(context, UserManager
								.getManager().getUser().userId + "message");
						long b = 1;
						try {
							db.saveMessage(mes);
							if (db.isExit()) {
								b = db.getNewMessageNum();
							}
						} catch (DbException e) {
							Tools.handle(e);
						}

						showmsg = "亲,您有" + b + "个新的消息通知，请及时查看。";
						Intent intent = new Intent(AppContext.MESSAGE_SYSTEM);
						context.sendBroadcast(intent);
						Intent myintent;
						if (AppContext.islogining) {
							myintent = new Intent(context,
									MessageActivity.class);
						} else {
							myintent = new Intent(context,
									WelcomeActivity.class);
						}
						contentIntent = PendingIntent.getActivity(context, 1,
								myintent, 0);
						notifacation("消息通知", context, manager, contentIntent,
								showmsg, 2000, b);
					} else {
						tiXing(context, isVibrate, isMusic);// 系统消息提醒（声音，震动）
						String chatterType = json.getString("chatterType");
						String text = json.getString("content");
						String relatedId = json.getString("relatedId");
						if (chatterType.equals("follow")
								|| chatterType.equals("sendmessage")) {
							Message mes = new Message();
							mes.setContext(text);
							mes.setTime(Tools.getTime(System
									.currentTimeMillis()));
							mes.setIsNew("1");
							MessageDB db = new MessageDB(context, UserManager
									.getManager().getUser().userId + "message");
							long b = 1;
							try {
								db.saveMessage(mes);
								if (db.isExit()) {
									b = db.getNewMessageNum();
								}
							} catch (DbException e) {
								Tools.handle(e);
							}
							showmsg = "亲,您有" + b + "个新的消息通知，请及时查看。";
							Intent intent = new Intent(
									AppContext.MESSAGE_SYSTEM);
							context.sendBroadcast(intent);
							Intent myintent;
							if (AppContext.islogining) {
								myintent = new Intent(context,
										MessageActivity.class);
							} else {
								myintent = new Intent(context,
										WelcomeActivity.class);
							}
							contentIntent = PendingIntent.getActivity(context,
									1, myintent, 0);
							notifacation("消息通知", context, manager,
									contentIntent, showmsg, 2000, b);
						} else {
							Intent myintent;
							if (AppContext.islogining) {
								myintent = new Intent(context,
										AboutMeActivty.class);//
							} else {
								myintent = new Intent(context,
										WelcomeActivity.class);
							}
							contentIntent = PendingIntent.getActivity(context,
									1, myintent, 0);
							AppContext.atnum++;
							int a = AppContext.atnum;
							ChatMessageDB db = new ChatMessageDB(context,
									UserManager.getManager().getUser().userId
											+ "chat");
							ChatMessage chat = new ChatMessage();
							chat.setIsNew("1");
							chat.setChatterType(chatterType);
							chat.setContext(text);
							chat.setRelatedId(relatedId);
							chat.setTime(Tools.getTime(System
									.currentTimeMillis()));
							try {
								db.saveChatMessage(chat);
							} catch (DbException e) {
								e.printStackTrace();
							}
							Intent chatIntent = new Intent(
									AppContext.MESSAGE_CHATMESSAGE);
							context.sendBroadcast(chatIntent);
							showmsg = text.trim();
							notifacation("chat消息通知", context, manager,
									contentIntent, showmsg, 2004, a);
						}
					}
				} else if (function.equals("IM")) {
					tiXing(context, isVibrate, isMusic);// 系统消息提醒（声音，震动）
					JSONObject jsonString = json.getJSONObject("pushMessage");
					IMMessage IMmessage = (IMMessage) Json.toObject(
							jsonString.toString(), IMMessage.class);
					IMmessage.setFromOrTo(0);
					IMmessage
							.setTime(Tools.getTime(System.currentTimeMillis()));
					IMmessage.setIsNew("1");
					// IMmessage.setMessage("http://jb.sznews.com/res/1/1161/2014-03/12/B02/res04_attpic_brief.jpg");
					// IMmessage.setMessageType("3");
					IMmessage.setSuccess(true);
					IMmessage.setMessageId(IMmessage.getFromUserId());
					RecentItem recent = new RecentItem();
					recent.setFromUserId(IMmessage.getFromUserId());
					recent.setFromUserName(IMmessage.getFromUserName());
					if (IMmessage.getMessageType().equals("1")) {
						recent.setMessage(IMmessage.getMessage());
						recent.setMessageType("1");
					} else if (IMmessage.getMessageType().equals("2")) {
						recent.setMessage("语音");
						recent.setMessageType("2");
					} else {
						recent.setMessage("图片");
						recent.setMessageType("3");
					}
					recent.setMessageId(IMmessage.getFromUserId());
					recent.setName("炸酱面");
					recent.setTime(System.currentTimeMillis());
					recent.setUser_id(UserManager.getManager().getUser().userId);
					IMMessageDB Db = new IMMessageDB(context, UserManager
							.getManager().getUser().userId + "IM");
					RecentDB recentdb = new RecentDB(context, UserManager
							.getManager().getUser().userId + "RecentItem");
					try {
						Db.saveIMMessage(IMmessage);
						recentdb.saveRecentList(recent);
					} catch (DbException e) {
						e.printStackTrace();
					}
					/**
					 * IM消息广播
					 */
					Intent intent = new Intent(AppContext.IM_MESSAGE);
					intent.putExtra("IM", IMmessage);
					context.sendBroadcast(intent);
				}
			} else if (messageType.equals("notification")) {
				String function = json.getString("function");
				if (function.equals("approval")) {// 审批通知
					tiXing(context, isVibrate, isMusic);// 审批提醒（声音，震动）

					Intent myintent;
					if (AppContext.islogining) {
						myintent = new Intent(context, TaskManagementActivty.class);
					} else {
						myintent = new Intent(context, WelcomeActivity.class);
					}
					myintent.putExtra("MyPushMessageReceiver", "approval");
					contentIntent = PendingIntent.getActivity(context, 1,
							myintent, 0);
					AppContext.dspnum++;
					int a = AppContext.dspnum;
					ApprovalDB db = new ApprovalDB(context, UserManager
							.getManager().getUser().userId + "chat");
					Approval app = new Approval();
					app.setIsNew("1");
					try {
						db.saveApproval(app);
					} catch (DbException e) {
						e.printStackTrace();
					}
					Intent dspintent = new Intent(AppContext.MESSAGE_DAISHENPI);
					context.sendBroadcast(dspintent);
					showmsg = "亲,您有" + a + "个新的审批工作，请及时处理。";
					notifacation("待审批通知", context, manager, contentIntent,
							showmsg, 2002, a);
				} else if (function.equals("taskAlert")) {// 任务过期提醒
					tiXing(context, isVibrate, isMusic);// 任务提醒（声音，震动）
					Intent myintent;
					if (AppContext.islogining) {
						myintent = new Intent(context, WebViewActivity.class);
					} else {
						myintent = new Intent(context, WelcomeActivity.class);
					}
					myintent.putExtra("MyPushMessageReceiver", "task");
					contentIntent = PendingIntent.getActivity(context, 2,
							myintent, 0);
					AppContext.rwnum++;
					int b = AppContext.rwnum;
					TaskDB db = new TaskDB(context, UserManager.getManager()
							.getUser().userId + "chat");
					Task task = new Task();
					task.setIsNew("1");
					try {
						db.saveTask(task);
					} catch (DbException e) {
						e.printStackTrace();
					}
					Intent dspintent = new Intent(
							AppContext.MESSAGE_DAIBANRENWU);
					context.sendBroadcast(dspintent);
					showmsg = "亲,您有" + b + "个新的工作任务，请及时处理。";
					notifacation("任务通知", context, manager, contentIntent,
							showmsg, 2001, b);
				} else if (function.equals("eventAlert")) {// 事件消息推送
					tiXing(context, isVibrate, isMusic);// 事件提醒（声音，震动）
					Intent myintent;
					if (AppContext.islogining) {
						myintent = new Intent(context, WebViewActivity.class);
					} else {
						myintent = new Intent(context, WelcomeActivity.class);
					}
					myintent.putExtra("MyPushMessageReceiver", "event");
					contentIntent = PendingIntent.getActivity(context, 4,
							myintent, 0);
					AppContext.eventnum++;
					int b = AppContext.eventnum;
					EventDB db = new EventDB(context, UserManager.getManager()
							.getUser().userId + "chat");
					Event event = new Event();
					event.setIsNew("1");
					try {
						db.saveEvent(event);
					} catch (DbException e) {
						e.printStackTrace();
					}
					Intent dspintent = new Intent(
							AppContext.MESSAGE_RICHENG_EVENT);
					context.sendBroadcast(dspintent);
					showmsg = "亲,您有" + b + "个新的日程事件，请及时处理。";
					notifacation("日程事件通知", context, manager, contentIntent,
							showmsg, 2003, b);
				}

			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 是否提醒
	 * 
	 * @param context
	 * @param isZhengdong
	 * @param isMusic
	 */
	private void tiXing(Context context, boolean isZhengdong, boolean isMusic) {
		if (isZhengdong) {// 震动提醒
			Vibrator vibrator = (Vibrator) context
					.getSystemService(Service.VIBRATOR_SERVICE);
			long[] pattern = { 1000, 1000, 1000, 1000, 1000 }; // OFF/ON/OFF/ON...
			vibrator.vibrate(pattern, -1);
		}
		if (isMusic) {// 声音提醒
			LogUtils.d("app","声音提示参数："+isMusic);
			MediaPlayer music = MediaPlayer.create(context, R.raw.cloudcc);
			music.start();
		}
	}

	public void notifacation(String name, final Context context,
			NotificationManager manager, PendingIntent contentIntent,
			String showmsg, int a, long b) {// 消息2000，任务2001，待审批2002
		NotificationCompat.Builder builder = new NotificationCompat.Builder(
				context)
				.setSmallIcon(R.drawable.icon)
				// .setLargeIcon(BitmapFactory.decodeResource(context.getResources(),
				// R.drawable.icon))
				.setContentTitle(name)
				.setContentText(showmsg)
				// .setLargeIcon(BitmapFactory.decodeResource(context.getResources(),R.drawable.icon))
				.setContentInfo("" + b).setTicker("亲，来消息了").setAutoCancel(true)
				.setContentIntent(contentIntent)
				.setDefaults(Notification.DEFAULT_LIGHTS);

		// 发送通知
		manager.notify(a, builder.build());
	}

	/**
	 * 接收通知点击的函数。注：推送通知被用户点击前，应用无法通过接口获取通知的内容。
	 */
	@Override
	public void onNotificationClicked(Context context, String title,
			String description, String customContentString) {
	}

	/**
	 * setTags() 的回调函数。
	 * 
	 */
	@Override
	public void onSetTags(Context context, int errorCode,
			List<String> sucessTags, List<String> failTags, String requestId) {
		String responseString = "onSetTags errorCode=" + errorCode
				+ " sucessTags=" + sucessTags + " failTags=" + failTags
				+ " requestId=" + requestId;
	}

	/**
	 * delTags() 的回调函数。
	 */
	@Override
	public void onDelTags(Context context, int errorCode,
			List<String> sucessTags, List<String> failTags, String requestId) {
	}

	/**
	 * listTags() 的回调函数。
	 * 
	 */
	@Override
	public void onListTags(Context context, int errorCode, List<String> tags,
			String requestId) {
	}

	/**
	 * PushManager.stopWork() 的回调函数。
	 */
	@Override
	public void onUnbind(Context context, int errorCode, String requestId) {
	}

	@Override
	public void onNotificationArrived(Context arg0, String arg1, String arg2,
			String arg3) {
		
	}

}
